#pragma once
#include <vector>
#include <iostream>
#include <fstream>
#include "..\Course\hr_time.h"
#include <functional>

using namespace std;

namespace U32
{
	struct data
	{
		long long sum; // sum of salaries for this interval
		int n; // amount of people in this interval
		data()
		{
			sum = 0;
			n = 0;
		}
	};

	class Statistics
	{
	private:
		vector<data> salaries;
	public:

		Statistics()
		{
			Clear();
		}

		~Statistics()
		{
		}
		
		void Clear()
		{
			for (int i = 0; i < 1000; i++)
			{
				salaries.push_back(data());
			}
		}

		void ReadFromFile()
		{
			ifstream fin;
			fin.open("salary.txt");
			int kr;
			int interval = 1000;
			int index = 0;
			while (fin.good())
			{
				fin >> kr;
				if (kr < 1000000)
				{
					index = kr / interval + 0.5;
					salaries[index].sum += kr;
					salaries[index].n++;
				}
			}
		}

		int CalculateMean()
		{
			int noOfSalaries = 0;
			long long total = 0;
			for (auto s : salaries)
			{
				noOfSalaries += s.n;
				total += s.sum;
			}

			return total / noOfSalaries;
		}

		int Percentile(float percentile)
		{
			int rank = 0;
			int noOfSalaries = 0;
			for (auto s : salaries)
			{
				noOfSalaries += s.n;
			}
			rank = (percentile / 100) * noOfSalaries;
			noOfSalaries = 0;
			int index = 0;
			for (auto s : salaries)
			{
				noOfSalaries += s.n;
				if (noOfSalaries > rank)
				{
					break;
				}
				index++;
			}


			return index * 1000 + 1000;
		}

		void mainU32()
		{
			cout << ">>>>> Uppgift 3.2 <<<<<" << endl;
			CStopWatch sw;
			sw.startTimer();
			ReadFromFile();
			cout << "The mean of all the salaries is: " << CalculateMean() << " kr" << endl;
			cout << "25th percentile: " << Percentile(25) << " kr" << endl;
			cout << "50th percentile: " << Percentile(50) << " kr" << endl;
			cout << "75th percentile: " << Percentile(75) << " kr" << endl;
			cout << "90th percentile: " << Percentile(90) << " kr" << endl;
			cout << "99th percentile: " << Percentile(99) << " kr" << endl;
			sw.stopTimer();
			cout << "Time elapsed: " << sw.getElapsedTime() << " seconds." << endl << endl;
		}
	};
}

